//
//  Connector.m
//  Exchange
//
//  Created by Александр Лазарекно on 08.12.12.
//  Copyright (c) 2012 Бонч. All rights reserved.
//

#import "Connector.h"
#import "GDataXMLNode.h"
@implementation Connector 
@synthesize dataFromServer=_dataFromServer;
@synthesize delegate=_delegate;

- (void) dealloc {
    [_dataFromServer release];
    [super dealloc];
}

- (id) initWithDelegate:(id<ConnectionDelegate>)delegate {
    self = [super init];
    if (self) {
        _delegate = delegate;
    }
    return self;
}
- (void) sendRequestToServerWithBody:(NSData*) soapBody {
    NSURL* urlServer = [[NSURL alloc]initWithString:@"https://mail.digdes.com/ews/exchange.asmx"];
    NSMutableURLRequest* theRequest = [[NSMutableURLRequest alloc]initWithURL:urlServer];
    [theRequest addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
    //[theRequest addValue:@"http://schemas.microsoft.com/sharepoint/soap/GetListCollection" forHTTPHeaderField:@"SOAPAction"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:soapBody];
    NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
    if (connect) {
        _dataFromServer = [[NSMutableData alloc]init];
    }
    else {
        NSLog(@"No Connection established");
    }
    
}

- (void) connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"Authentification error");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_dataFromServer setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_dataFromServer appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction");
    [connection release];
}

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return YES;
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"sed" password:@"P@ssw0rd" persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  NSLog(@"connection did finish loading");
    [self.delegate didFinishLoadingData:_dataFromServer];
    _dataFromServer = nil;
    [connection release];
}





@end
